import 'dart:async';
import 'dart:ui';

import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_view.dart';
import 'package:get/get_utils/src/extensions/internacionalization.dart';
import 'package:intl/intl.dart';
import 'package:mziot/app/config/design.dart';
import 'package:mziot/app/modules/scene/controllers/scene_detail_controller.dart';
import 'package:mziot/generated/assets.dart';
import 'package:mziot/generated/locales.g.dart';

class SceneDetailView extends GetView<SceneDetailController> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.scene_add_title.tr),
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
        },
        child: Container(
          color: Colors.white,
          width: double.infinity,
          child: SafeArea(
            child: Container(
              child: Obx(() {
                final change = controller.infoChange.value;

                return Column(
                  children: [
                    Expanded(
                      child: ListView.builder(
                        itemCount: 6,
                        itemBuilder: (ctx, index) {
                          if (index == 0) {
                            return _nameView;
                          } else if (index == 1) {
                            return _chooseView;
                          } else if (index == 2) {
                            return _timeView;
                          } else if (index == 3) {
                            return _lightView;
                          } else if (index == 4) {
                            return _lockView;
                          }
                          return _noteView;
                        },
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.symmetric(horizontal: 12),
                      child: TextButton(
                        onPressed: () {
                          FocusManager.instance.primaryFocus?.unfocus();
                          Future.delayed(Duration(milliseconds: 300), () {
                            controller.editAction();
                          });
                        },
                        style: ButtonStyle(
                          shape: MaterialStateProperty.all(StadiumBorder()),
                          backgroundColor: MaterialStateProperty.all(MColor.skin),
                        ),
                        child: Text(
                          LocaleKeys.public_save.tr,
                          style: MFont.regular13.apply(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                );
              }),
            ),
          ),
        ),
      ),
    );
  }

  get _nameView {
    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            color: MColor.xFFF2F2F2,
            height: 8,
          ),
          Container(
            color: Colors.white,
            height: 16,
          ),
          Padding(
            padding: EdgeInsets.only(left: 12),
            child: Text(
              LocaleKeys.scene_name.tr,
              style: MFont.semi_Bold13.apply(color: MColor.xFF333333),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 12, right: 12),
            child: TextField(
              controller: controller.nameController,
              decoration: InputDecoration(
                hintText: LocaleKeys.public_input.tr,
                hintStyle: MFont.regular15.apply(color: MColor.xFF333333_60),
                enabledBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: MColor.xFFCCCCCC, width: 0.5),
                ),
                focusedBorder: UnderlineInputBorder(
                  borderSide: BorderSide(color: MColor.xFF000000, width: 1),
                ),
              ),
              textAlignVertical: TextAlignVertical.bottom,
              onChanged: (text) {
                controller.sceneInfo.value.sceneName = text;
              },
            ),
          )
        ],
      ),
    );
  }

  get _timeView {
    final startDate = controller.sceneInfo.value.startTime ?? LocaleKeys.scene_time_start.tr;
    final endDate = controller.sceneInfo.value.endTime ?? LocaleKeys.scene_time_end.tr;

    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 12, right: 12, top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            LocaleKeys.scene_time.tr,
            style: MFont.semi_Bold13.apply(color: MColor.xFF333333),
          ),
          Row(
            children: [
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                child: Container(
                  padding: EdgeInsets.only(top: 12, bottom: 8),
                  width: 100,
                  child: Text(
                    startDate,
                    style: MFont.regular14.apply(color: MColor.xFF666666),
                  ),
                ),
                onTap: () {
                  FocusManager.instance.primaryFocus?.unfocus();
                  showDate(true);
                },
              ),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  FocusManager.instance.primaryFocus?.unfocus();
                  showDate(true);
                },
                child: Icon(
                  Icons.arrow_forward,
                  size: 20,
                  color: MColor.xFFCCCCCC,
                ),
              ),
              Expanded(
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () {
                    FocusManager.instance.primaryFocus?.unfocus();
                    showDate(false);
                  },
                  child: Container(
                    padding: EdgeInsets.only(left: 32, top: 12, bottom: 8),
                    child: Text(
                      endDate,
                      style: MFont.regular14.apply(color: MColor.xFF666666),
                    ),
                  ),
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  FocusManager.instance.primaryFocus?.unfocus();
                  showDate(false);
                },
                child: Icon(
                  Icons.keyboard_arrow_right_outlined,
                  size: 20,
                  color: MColor.xFFCCCCCC,
                ),
              ),
            ],
          ),
          Divider(height: 1, color: MColor.xFFCCCCCC),
        ],
      ),
    );
  }

  get _lightView {
    final momentVos = controller.sceneInfo.value.lightOffs ?? [];
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 12, right: 12, top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            LocaleKeys.scene_light_on.tr,
            style: MFont.semi_Bold13.apply(color: MColor.xFF333333),
          ),
          SizedBox(height: 12),
          Column(
            children: [
              for (int i = 0; i < momentVos.length; i++) ...{
                _lightTimeView(i),
                if (i < momentVos.length - 1) ...{
                  SizedBox(height: 16),
                  Divider(height: 1, color: MColor.xFFCCCCCC),
                  SizedBox(height: 16),
                }
              },
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  _showCupertinoDatePicker();
                },
                child: Container(
                    decoration: BoxDecoration(
                      color: MColor.xFFF2F2F2,
                      borderRadius: BorderRadius.circular(5),
                    ),
                    height: 35,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '+',
                          style: MFont.semi_Bold24.apply(color: Colors.black),
                        ),
                        SizedBox(width: 2),
                        Text(
                          LocaleKeys.scene_add.tr,
                          style: MFont.regular13.apply(color: MColor.xFF333333),
                        ),
                      ],
                    )),
              ),
            ],
          ),
          SizedBox(height: 8),
        ],
      ),
    );
  }

  Widget _lightTimeView(int index) {
    final startTime = controller.sceneInfo.value.lightOffs?[index].start ?? '';
    final endTime = controller.sceneInfo.value.lightOffs?[index].end ?? '';
    final rate = controller.sceneInfo.value.lightOffs?[index].rate ?? 10;
    final count = controller.sceneInfo.value.lightOffs?.length ?? 0;
    final showBottom = index == count - 1;
    return Container(
      padding: EdgeInsets.only(bottom: showBottom ? 20 : 0),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              Image.asset(
                Assets.imagesSceneLighting,
                width: 32,
                height: 32,
              ),
              SizedBox(width: 8),
              Text(
                startTime + ' - ' + endTime,
                style: MFont.regular15.apply(color: MColor.xFF333333),
              ),
              Spacer(),
              Obx(() {
                final rate = controller.sceneInfo.value.lightOffs?[index].rate ?? 10;

                return Container(
                  padding: EdgeInsets.only(bottom: 5),
                  child: RateTextField(rate, (value) {
                    controller.updateLight(value, index);
                  }),
                );
              }),
              SizedBox(width: 5),
              Text(
                '%',
                style: MFont.regular13.apply(
                  color: MColor.xFF333333,
                ),
              ),
              SizedBox(width: 8),
              GestureDetector(
                onTap: () {
                  controller.deleteAction(index);
                },
                child: Image.asset(
                  Assets.imagesSceneLightDelete,
                  width: 20,
                  height: 20,
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(left: 28, top: 6, right: 28, bottom: 0),
            child: SliderTheme(
              data: SliderThemeData(
                trackHeight: 22,
                thumbColor: Colors.white,
                activeTrackColor: MColor.skin,
                inactiveTrackColor: MColor.xFFF2F2F2,
                overlayShape: RoundSliderOverlayShape(overlayRadius: 0),
              ),
              child: Slider(
                min: 10,
                max: 100,
                value: rate.toDouble(),
                onChanged: (number) {
                  FocusManager.instance.primaryFocus?.unfocus();
                  controller.updateLight(number.toInt(), index);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  get _chooseView {
    final groupName = controller.selectText.value;
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 12, right: 12, top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            LocaleKeys.scene_choose_group.tr,
            style: MFont.semi_Bold13.apply(color: MColor.xFF333333),
          ),
          SizedBox(height: 12),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              FocusManager.instance.primaryFocus?.unfocus();
              controller.openChooseAction();
            },
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    groupName.isEmpty ? LocaleKeys.scene_choose_more.tr : groupName,
                    style: MFont.regular13
                        .apply(color: MColor.xFF999999, overflow: TextOverflow.ellipsis),
                    maxLines: 1,
                  ),
                ),
                Icon(
                  Icons.keyboard_arrow_right_outlined,
                  size: 20,
                  color: MColor.xFFCCCCCC,
                ),
              ],
            ),
          ),
          SizedBox(height: 8),
          Divider(height: 1, color: MColor.xFFCCCCCC),
        ],
      ),
    );
  }

  get _lockView {
    final lock = controller.sceneInfo.value.isLock ?? false;
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 12, right: 12, top: 24, bottom: 12),
      child: Row(
        children: [
          Text(
            LocaleKeys.scene_lock.tr,
            style: MFont.semi_Bold13.apply(color: MColor.xFF333333),
          ),
          Spacer(),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              FocusManager.instance.primaryFocus?.unfocus();
              controller.sceneInfo.value.isLock = !lock;
              controller.infoChange.value = !controller.infoChange.value;
            },
            child: Image.asset(
              lock ? Assets.imagesSceneOpen : Assets.imagesSceneClose,
              width: 47,
              height: 24,
            ),
          ),
        ],
      ),
    );
  }

  get _noteView {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 12, right: 12, top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            LocaleKeys.scene_note.tr,
            style: MFont.semi_Bold13.apply(color: MColor.xFF333333),
          ),
          TextField(
            controller: controller.noteController,
            decoration: InputDecoration(
              hintText: LocaleKeys.public_input.tr,
              hintStyle: MFont.regular15.apply(color: MColor.xFF333333_60),
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: MColor.xFFCCCCCC, width: 0.5),
              ),
              focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: MColor.xFF000000, width: 1),
              ),
            ),
            textAlignVertical: TextAlignVertical.bottom,
            onChanged: (text) {
              controller.sceneInfo.value.remark = text;
            },
          )
        ],
      ),
    );
  }

  void _showCupertinoDatePicker() {
    controller.dateStart.value = DateTime.now();
    controller.dateEnd.value = DateTime.now();

    controller.selectDate.value = false;
    showCupertinoModalPopup(
        context: Get.context!,
        builder: (cxt) {
          return Container(
            height: 350,
            color: Colors.white,
            child: Column(
              children: [
                _topView,
                Expanded(
                  child: CupertinoDatePicker(
                    onDateTimeChanged: (date) {
                      final left = controller.selectLeft.value;
                      if (left) {
                        controller.dateStart.value = date;
                      } else {
                        controller.dateEnd.value = date;
                      }
                    },
                    mode: CupertinoDatePickerMode.time,
                    initialDateTime: DateTime.now(),
                  ),
                ),
              ],
            ),
          );
        });
  }

  void showDate(bool left) {
    controller.selectLeft.value = left;
    controller.selectDate.value = true;
    controller.dateStart.value = DateTime.now();
    controller.dateEnd.value = DateTime.now();

    DateFormat format = DateFormat("yyyy-MM-dd");
    if (controller.sceneInfo.value.startTime != null) {
      final startTime = format.parse(controller.sceneInfo.value.startTime!);
      controller.dateStart.value = startTime;
    }
    if (controller.sceneInfo.value.endTime != null) {
      final endTime = format.parse(controller.sceneInfo.value.endTime!);
      controller.dateEnd.value = endTime;
    }

    DatePicker.showDatePicker(
      Get.context!,
      dateFormat: 'yyyy-MM-dd',
      onChange: (time, values) {
        final left = controller.selectLeft.value;
        if (left) {
          controller.dateStart.value = time;
        } else {
          controller.dateEnd.value = time;
        }
      },
      pickerTheme: DateTimePickerTheme(
        backgroundColor: Colors.white,
        selectionOverlay: Container(),
        pickerHeight: 170,
        titleHeight: 170,
        itemHeight: 40,
        title: _topView,
        itemTextStyle: MFont.semi_Bold20.apply(color: MColor.xFF333333),
      ),
    );
  }

  get _topView {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          _titleView,
          Row(
            children: [
              Spacer(flex: 39),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  controller.selectLeft.value = true;
                },
                child: Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        LocaleKeys.scene_time_start.tr,
                        style: MFont.regular13.apply(color: MColor.xFF333333),
                      ),
                      SizedBox(height: 12),
                      Obx(() {
                        final dateStr =
                            formatDate(controller.dateStart.value, [yyyy, '-', mm, '-', dd]);
                        final timeStr =
                            formatDate(controller.dateStart.value, [hh, ':', nn, ' ', am]);

                        return Text(
                          controller.selectDate.value ? dateStr : timeStr,
                          style: controller.selectLeft.value
                              ? MFont.semi_Bold20.apply(color: MColor.skin)
                              : MFont.regular20.apply(color: MColor.xFF333333),
                        );
                      }),
                    ],
                  ),
                ),
              ),
              Spacer(flex: 59),
              Container(
                color: MColor.xFFCCCCCC,
                width: 1,
                height: 47,
                margin: EdgeInsets.symmetric(
                  horizontal: 39,
                  vertical: 40,
                ),
              ),
              Spacer(flex: 39),
              GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  controller.selectLeft.value = false;
                },
                child: Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        LocaleKeys.scene_time_end.tr,
                        style: MFont.regular13.apply(color: MColor.xFF333333),
                      ),
                      SizedBox(height: 12),
                      Obx(() {
                        final dateStr =
                            formatDate(controller.dateEnd.value, ['yyyy', '-', 'mm', '-', 'dd']);
                        final timeStr =
                            formatDate(controller.dateEnd.value, [hh, ':', nn, ' ', am]);

                        return Text(
                          controller.selectDate.value ? dateStr : timeStr,
                          style: !controller.selectLeft.value
                              ? MFont.semi_Bold20.apply(color: MColor.skin)
                              : MFont.regular20.apply(color: MColor.xFF333333),
                        );
                      }),
                    ],
                  ),
                ),
              ),
              Spacer(flex: 59),
            ],
          ),
        ],
      ),
    );
  }

  get _titleView {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 12),
            child: Text(
              LocaleKeys.devices_cancel.tr,
              style: MFont.regular13.apply(color: MColor.xFF333333),
            ),
          ),
        ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            controller.updateDate();
          },
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 12, horizontal: 12),
            child: Text(
              LocaleKeys.public_save.tr,
              style: MFont.regular13.apply(color: MColor.skin),
            ),
          ),
        ),
      ],
    );
  }
}

class RateTextField extends StatefulWidget {
  final ValueChanged? textChanged;
  final int rate;
  RateTextField(this.rate, this.textChanged, {Key? key}) : super(key: key) {}

  @override
  State<RateTextField> createState() => _State();
}

class _State extends State<RateTextField> {
  final TextEditingController editingController = TextEditingController();
  late StreamSubscription<bool> keyboardSubscription;

  @override
  void initState() {
    var keyboardVisibilityController = KeyboardVisibilityController();

    // Subscribe
    keyboardSubscription = keyboardVisibilityController.onChange.listen((bool visible) {
      if (!visible) {
        final text = editingController.text.trim();
        if (text.isNotEmpty) {
          var num = int.parse(text);
          if (num < 10) {
            num = 10;
          } else if (num > 100) {
            num = 100;
          }
          widget.textChanged!(num);
        } else {
          widget.textChanged!(10);
          editingController.selection = TextSelection(
              affinity: TextAffinity.downstream,
              baseOffset: editingController.text.length,
              extentOffset: editingController.text.length);
        }
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    editingController.text = '${widget.rate}';
    editingController.selection = TextSelection(
        affinity: TextAffinity.downstream,
        baseOffset: editingController.text.length,
        extentOffset: editingController.text.length);

    return Container(
      width: 40,
      child: TextField(
        controller: editingController,
        scrollPadding: EdgeInsets.zero,
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
          // isDense: true,
          isCollapsed: true,
          hintStyle: MFont.regular15.apply(color: MColor.xFF333333_60),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: MColor.xFFCCCCCC, width: 0.5),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: MColor.xFF000000, width: 1),
          ),
        ),
        textAlignVertical: TextAlignVertical.bottom,
      ),
    );
  }

  @override
  void dispose() {
    editingController.dispose();
    keyboardSubscription.cancel();
    super.dispose();
  }
}
